<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">


      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width:10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;" >
          <el-dropdown-item command="全部" >全部</el-dropdown-item>
          <el-dropdown-item v-for="(item,index) in tableTitle" :command="item.label" >{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false:true">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="addnew">新建</el-button>
    </el-header>
    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item,index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label" :width="item.width"></el-table-column>

        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <!-- 上传照片按钮 -->
            <el-button @click="handleUpload(scope.row)" type="text" size="small">上传照片</el-button>
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :rules="rules" :model="form" @submit.native.prevent>
        <el-form-item prop="name" label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>
        <div v-if="isCreateMode === false">
          <el-form-item prop="photo" label="照片" :label-width="formLabelWidth">
            <el-image
                style="width: 100px; height: 100px"
                :src="form.photo"
                fit="cover"
            ></el-image>
          </el-form-item>
        </div>
        <el-form-item prop="phone" label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.phone" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>

<!--        <div v-if="isCreateMode">-->
          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input
                v-model="form.password"
                type="password"
                autocomplete="off"
                :readonly="!isEditable"
                show-password
            ></el-input>
          </el-form-item>
<!--        </div>-->

        <el-form-item prop="idNumber" label="身份证号" :label-width="formLabelWidth">
          <el-input v-model="form.idNumber" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>

        <div v-if="isCreateMode === false">
          <el-form-item label="住址" :label-width="formLabelWidth">
            <el-input v-model="form.homeNumber" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item label="停车位" :label-width="formLabelWidth">
            <el-input v-model="form.parkingNumber" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item label="车牌号" :label-width="formLabelWidth">
            <el-input v-model="form.carNumber" autocomplete="off" readonly></el-input>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="isCreateMode === false">
          <el-button type="warning" @click="toggleEdit">编 辑</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="isCreateMode">
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>


<script>
import http from '@/utils/http';
import { checkToken } from '@/router/index';
import Vue from "vue"; // 导入checkToken函数

export default {
  data() {
    return {
      loading:false,
      filteredList:[],
      Filter:'全部',
      search :"",
      currentPage: 1,
      pageSize: 10,
      allInfo:[],
      tableTitle:[
        {tableProp:"id",label:"业主id"},
        {tableProp:"name",label:"姓名"},
        {tableProp:"phone",label:"手机号"},
        {tableProp:"idNumber",label:"身份证号"},
      ],
      tableData: [

      ],

      dialogFormVisible: false,
      isCreateMode: false, //是否为新建模式，新建模式要显示密码
      form: {
        id: '',
        name: '',
        photo: '',
        phone: '',
        password: '',
        idNumber: '',
        homeNumber: '',//只显示所有房号
        parkingNumber: '',//只显示所有停车位号
        carNumber: '',//只显示所有车牌号
        address: [],//所有房子信息
        parkingSpace: [],//所有停车位信息
        cars: []//所有车子信息
      },
      checked: true,
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度应在2~10之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 200, message: '密码长度应在6~200之间', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '身份证不能为空', trigger: 'blur' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}([0-9Xx])$/, message: '请输入有效的身份证号', trigger: 'blur' }
        ]
      },
      originalForm: null, // 保存原始数据副本
      isEditable: false, // 控制输入框是否可编辑
      dialogTitle: '', // 对话框标题
      formLabelWidth: '120px' // 标签宽度
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted(){
    this.getAllData();
  },
  methods: {
    handleRefresh(){
      this.getAllData();
    },
    //以调用后端获取所有数据
    getAllData(){
      this.loading=true;
      //console.log("Token: " + localStorage.getItem('userToken'));
     // console.log(localStorage.getItem('userToken'));
      http.get("/admin/landlord/getAllLandlord")
          .then((response)=>{
        console.log("request succeed!");
        // console.log(response);
        const Result = response.data;
        this.allInfo=Result.data;
        this.tableData=this.allInfo;
        this.loading=false;
        //this.setInfotoTable();
      }).catch(function (error){
        //请求失败
        console.log("request error !");
        console.error(error);
      });
    },
    setInfotoTable(){
      // 使用 tableProp 生成新数组
      const filteredList = this.allInfo.map(item => {
        let newItem = {};
        this.tableTitle.forEach(key => {
          if (item.hasOwnProperty(key.tableProp)) {
            newItem[key.tableProp] = item[key.tableProp];
          }
        });
        return newItem;
      });
      console.log(this.allInfo);
      console.log(filteredList);
      this.tableData=this.allInfo;
    },
    resetForm() {
      // 重置数据模型
      // 重置表单控件状态
      this.$nextTick(() => {
        this.form = {
          id: '',
          name: '',
          phone: '',
          password: '',
          idNumber: '',
          homeNumber: '',//只显示所有房号
          parkingNumber: '',//只显示所有停车位号
          carNumber: '',//只显示所有车牌号
          address: [],//所有房子信息
          parkingSpace: [],//所有停车位信息
          cars: []//所有车子信息
        };
        this.$refs.form.resetFields();
      });
    },
    //新建业主
    addnew() {
      // 需要重置表单数据
      setTimeout(()=>{
        this.resetForm();
      }, 100)
      this.dialogFormVisible = true;//显示对话框
      this.isEditable = true;//刚开始就能编辑
      this.isCreateMode = true; // 设置为新建模式
      this.dialogTitle = '新建业主';
    },
    //执行重置操作
    handleReset(){
      this.search="";
      this.Filter="全部";
      this.tableData=this.allInfo;
      this.tableData=this.allInfo;
    },
    //过滤条件选择
    handleFilter(command){
      this.Filter = command;

    },
    //搜索
    handleSearch(){
      if(this.search){
        if (this.Filter === "全部") {
          this.tableData = this.allInfo.filter(item => {
            return Object.keys(item).some(key => {
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });

          });
        }else{
          const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
          console.log(nowtable);
            this.tableData=this.allInfo
                .filter(
                item=>{
                  const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
                  return value.includes(this.search.toLowerCase());
                }
                   // item.name.toLowerCase().includes(this.search.toLowerCase())
            )
        }
      }

    },
    //上传照片按钮
    handleUpload(row) {
      // 创建一个input元素，让用户选择文件
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';//只接受图片文件
      fileInput.onchange = (event) => {
        const file = event.target.files[0];
        if (!file) {
          this.$message.error('请选择一个文件！');
          return;
        }
        const formData = new FormData();
        formData.append('id', row.id); // 假设每行数据有一个id属性
        formData.append('file', file);

        // 使用axios发送POST请求
        http.post('/admin/landlord/uploadPhoto', formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 设置请求头
          }
        })
            .then(response => {
              const Result = response.data;
              if (Result.success) {
                this.getAllData();
                this.$message.success('上传成功！');
                console.log("file", file);
              } else {
                this.$message.error(Result.errorMsg);
              }
            })
            .catch(error => {
              this.$message.error('上传失败，请重试！');
              console.log("file", file);
            });
      };
      fileInput.click(); // 触发文件选择
    },
    //详情按钮
    handleDetails(row) {
      console.log('业主详情', row);
      this.resetForm();
      // 根据业主id拿到对应的房、车、停车位信息
      http.get("/admin/landlord/getCarHouseById", {
        params: {
          id: row.id
        }
      })
          .then(response => {
            // 请求成功，处理响应数据
            const result = response.data;
            console.log(result.data);

            let tmp = '';
            this.allInfo.forEach((item, index) => {
              if (item.id === row.id) {
                 tmp = item.photo;
              }
            });
            this.form.photo = tmp;
            // console.log("this.form.photo", this.form.photo);

            this.form.id = row.id;
            this.form.name = row.name
            this.form.phone = row.phone;
            this.form.password = "********";
            this.form.idNumber = row.idNumber;
            // 拿到后端数据，这是一个列表
            this.form.address = result.data.house;
            this.form.parkingSpace = result.data.parks;
            this.form.cars = result.data.cars;
            // console.log(result.data.cars);
            this.form.homeNumber = this.form.parkingNumber = this.form.carNumber = '';

            // 将数据拼接为字符串
            for (let i = 0; i < this.form.address.length; i++) {
              this.form.homeNumber += this.form.address[i].number + ',';
            }
            for (let i = 0; i < this.form.parkingSpace.length; i++) {
              this.form.parkingNumber += this.form.parkingSpace[i].address + ',';
            }
            for (let i = 0; i < this.form.cars.length; i++) {
              this.form.carNumber += this.form.cars[i].number + ',';
            }

            // 处理字符串为空的情况
            if (this.form.homeNumber === '') {
              this.form.homeNumber = '无';
            } else {
              this.form.homeNumber = this.form.homeNumber.slice(0, -1);
            }
            if (this.form.parkingNumber === '') {
              this.form.parkingNumber = '无';
            } else {
              this.form.parkingNumber = this.form.parkingNumber.slice(0, -1);
            }
            if (this.form.carNumber === '') {
              this.form.carNumber = '无';
            } else {
              this.form.carNumber = this.form.carNumber.slice(0, -1);
            }
            // 之前放在请求外面，导致originalForm直接为空
            this.originalForm = { ...this.form }; // 深拷贝数据以保存状态
          })
          .catch(function (error) {
            // 请求失败，处理错误情况
            console.error(error);
            alert("请求失败！");
          });

      // this.form = { ...row }; // 将当前数据赋值给表单
      // console.log("test:", this.originalForm, this.form);
      this.dialogFormVisible = true;//显示对话框
      this.isEditable = false;//刚开始不能编辑
      this.isCreateMode = false; // 设置为详情模式
      this.dialogTitle = '业主详情|信息编辑';
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({

          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deleteData(row){
      // 删除界面上的
      this.tableData = this.tableData.filter(item=>item!=row);
      // 更新总数据源
      this.allInfo = this.tableData;

      // 检查当前页是否大于删除后的数据页数，若是则重置为前一页
      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      // //删除数据库中
      http.get("/admin/landlord/deleteLandlord",{
        params:{
          id: row.id
        }
      }).then(response=>{
        console.log(response.data.data);
      })
      }
    ,
    handlePageChange(page) {
      this.currentPage = page;
    },
    // 点击编辑按钮能编辑
    toggleEdit() {
      this.$message.warning("正在进行编辑");
      this.isEditable = true;
    },
    cancel() {
      // 恢复到编辑前的状态
      if (this.isCreateMode === false) {
        this.form = { ...this.originalForm };
      }
      this.dialogFormVisible = false;
      // 重置编辑状态
      this.isEditable = false;
    },
    // 确认添加
    confirmAdd() {
      this.$refs.form.validate((valid) => {
        // console.log(this.form);
        if (valid) {
          http.get("/admin/landlord/addLandlord", {
            params: {
              name: this.form.name,
              phone: this.form.phone,
              password: this.form.password,
              idNumber: this.form.idNumber,
            }
          })
              .then(response => {
                // 请求成功，处理响应数据
                console.log(response);
                const Result = response.data;
                if (Result.success) {
                  // 添加成功
                  this.getAllData();
                  this.$message.success("添加成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                } else {
                  // 添加失败
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(function (error) {
                // 请求失败，处理错误情况
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复编辑前的状态
          // this.form = { ...this.originalForm };
          return false;
        }
      });
    },
    // 确认修改
    confirm() {
      this.$refs.form.validate((valid) => {
        console.log("originalForm1", this.originalForm);
        if (valid) {
          let payload = {
            id: this.form.id,
            name: this.form.name,
            password: this.form.password,
            idNumber: this.form.idNumber
          };
          if (this.form.phone !== this.originalForm.phone) {
            payload.phone = this.form.phone;
          }
          http.post('/admin/landlord/updateLandlord', payload)
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAllData();
                  this.$message.success("修改成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                  console.log('Success:', response.data);
                } else {
                  this.$message.error(Result.errorMsg);
                  console.log('Error:', response.data);
                }
              })
              .catch(error => {
                this.$message.error("请求失败！")
                console.error('Error:', error);
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复到编辑前的状态
          console.log("originalForm2", this.originalForm);
          this.form = { ...this.originalForm };
          console.log(this.form);
          // return false;
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
</style>
